package com.log.listener;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.log.model.EventMessage;
import com.log.model.dto.LogInfoDTO;
import com.log.service.LogInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassDescription:
 * @Author: zhaoyi
 * @Created: 2024/7/18 14:40
 */
@Component
@Slf4j
public class RabbitMqListener {

    @Autowired
    private LogInfoService logInfoService;

    @RabbitListener(queues = "log_topic_queue")
    public void ListenerQueue(EventMessage eventMessage, Message message){
        log.info("监听到消息messageId:{} ",message);
        // 开始时间（ms）
        long l = System.currentTimeMillis();
        try{
            String content = eventMessage.getContent();
            LogInfoDTO dto = JSONObject.parseObject(content, new TypeReference<LogInfoDTO>() {});
            logInfoService.addLog(dto);
//            JSONArray jsonArray = JSONObject.parseArray(content);
//            List<LogInfoDTO> logInfoDTOS = JSONArray.parseObject(jsonArray.toJSONString(), new TypeReference<List<LogInfoDTO>>() {});
//            logInfoService.syncAndInsertLog(logInfoDTOS);
        }catch (Exception e){
            log.error("消费者失败:{}",eventMessage);
        }
        log.info("消费成功:{}",eventMessage.getContent());
        // 执行结束时间
        long end_l = System.currentTimeMillis();
        log.info("总耗时:{} ms", (end_l - l));

    }
}
